package com.servlet; /**
 * @author wzm
 * @create 2023-03-16 15:05
 */

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilterCheck implements Filter {
    public void init(FilterConfig config) throws ServletException {

    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
//        chain.doFilter(request, response);
       HttpServletRequest req = (HttpServletRequest) request;


        //逻辑 如果是符合要求的路径直接要放行    如果不符合要求 看是否登录 登录后则放行  没登录去登录

        //1.对于登录和注册相关的页面和css js 图片等内容需要直接放行  定义数组 放行的路径存储起来
        String[] urls = {"/login.jsp","/imgs","/css/","/login","/register.jsp","/register","/code.jpg"};

        //2.获取当前访问的资源路径
        String s = req.getRequestURL().toString();//javaweb09/login

        //3.比较当前访问的路径是不是数组中需要放行的 是就放行
        for (String u : urls){
            if(s.contains(u)){//判断当前访问的资源路径中是否包含了数组中元素的某个字符串
                //找到了
                chain.doFilter(request, response);
                return;
            }
        }

        //当期路径中没有包含需要放行的关键字  看是否登录

        //1.获取登录Session中的值
        Object loginUser = req.getSession().getAttribute("loginUser");

        //2.判断是否登录
        if(loginUser != null){
            //已经登录
            chain.doFilter(request, response);//放行
        }else{
            //没有登录
            req.getSession().setAttribute("msg", "您尚未登录");
            req.getRequestDispatcher("/login.jsp").forward(request,response);
        }


    }
}
